<template>
	<view class="container">
		<view class="reader-box" v-if="isScanning">
			<view class="reader" id="reader" ></view>
		</view>
	</view>
</template>

<script>
	import {
		Html5Qrcode
	} from 'html5-qrcode';

	export default {
		name: 'QRCodeScanner',
		data() {
			return {
				html5Qrcode: null,
				isScanning: false, // 扫描状态
			};
		},
		mounted() {
			this.startScan(); // 组件挂载后开始扫描
		},
		methods: {
			startScan() {
				this.isScanning = true;
				Html5Qrcode.getCameras().then(devices => {
					if (devices && devices.length) {
						this.html5Qrcode = new Html5Qrcode('reader');
						this.html5Qrcode.start({
								facingMode: 'environment'
							}, {
								fps: 24,
								qrbox: 280
							},
							(decodeText, decodeResult) => {
								if (decodeText) {
									this.$emit("decodeText", JSON.parse(decodeText));
									this.stopScan();
								}
							},
							(err) => {
								console.log(err);
							}
						);
					}
				});
			},
			stopScan() {
				if (this.html5Qrcode) {
					this.html5Qrcode.stop().then(() => {
						this.isScanning = false;
					}).catch(err => {
						console.error(err);
					});
				}
			}
		},
		beforeDestroy() {
			this.stopScan();
		}
	};
</script>

<style scoped>
	.container {
		width: 100vw;
		height: 100vh;

	}

	.reader-box {
		width: 100vw;
		height: 100vh;
	}

	#reader {
	}
	.qr-canvas{
	}
</style>